<template>
  <div class="exception-page">
    <!-- 筛选区 -->
    <el-form :inline="true" @submit.native.prevent class="filter-form">
      <el-form-item label="异常类型">
        <el-select v-model="filters.type" placeholder="请选择异常类型" clearable style="width: 180px">
          <el-option label="全部" value="" />
          <el-option v-for="item in exTypeOptions" :key="item.code" :label="item.name" :value="item.name" />
        </el-select>
      </el-form-item>
      <el-form-item label="严重程度">
        <el-select v-model="filters.severity" placeholder="请选择严重程度" clearable style="width: 180px">
          <el-option label="全部" value="" />
          <el-option v-for="item in exSeverityOptions" :key="item.code" :label="item.name" :value="item.name" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-input v-model="filters.keyword" placeholder="搜索异常单号/订单号/留言" clearable style="width: 220px" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="fetchList">查询</el-button>
        <el-button @click="resetFilters">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 新建异常单按钮 -->
    <div class="create-btn-bar">
      <el-button type="success" @click="showCreateDialog = true">新建异常单</el-button>
    </div>

    <!-- 异常单列表 -->
    <el-table :data="exceptionList" style="width: 100%;" stripe border class="exception-table" @row-click="openDetail">
      <el-table-column prop="id" label="异常单号" width="120" header-cell-class-name="table-header" />
      <el-table-column prop="order_id" label="订单号" width="120" header-cell-class-name="table-header" />
      <el-table-column prop="type" label="类型" width="100" header-cell-class-name="table-header" />
      <el-table-column prop="status" label="状态" width="100" header-cell-class-name="table-header" />
      <el-table-column prop="created_at" label="创建时间" width="180" header-cell-class-name="table-header" />
      <el-table-column prop="desc" label="描述" header-cell-class-name="table-header" />
    </el-table>
    <el-pagination
      v-model:current-page="pagination.page"
      :page-size="pagination.size"
      :total="pagination.total"
      @current-change="fetchList"
      layout="total, prev, pager, next"
      style="margin-top: 16px; text-align: right;"
    />

    <!-- 新建异常单弹窗 -->
    <el-dialog v-model="showCreateDialog" title="新建异常单" width="500px">
      <el-form :model="createForm" label-width="90px" class="create-form">
        <el-form-item label="任务包号">
          <el-select v-model="createForm.package_id" placeholder="请选择任务包" @change="handlePackageChange" clearable style="width: 100%">
            <el-option v-for="pkg in deliveringPackages" :key="pkg.packageId" :label="pkg.packageId" :value="pkg.packageId" />
          </el-select>
        </el-form-item>
        <el-form-item label="订单号">
          <el-select v-model="createForm.order_id" placeholder="请选择订单号" @change="handleOrderChange" clearable style="width: 100%">
            <el-option v-for="order in packageOrders" :key="order.orderNumber" :label="order.orderNumber" :value="order.orderNumber" />
          </el-select>
        </el-form-item>
        <el-form-item label="客户名称">
          <el-input v-model="createForm.customer" disabled style="width: 100%" />
        </el-form-item>
        <el-form-item label="联系电话">
          <el-input v-model="createForm.phone" disabled style="width: 100%" />
        </el-form-item>
        <el-form-item label="配送地址">
          <el-input v-model="createForm.address" disabled style="width: 100%" />
        </el-form-item>
        <el-form-item label="类型">
          <el-select v-model="createForm.type" placeholder="请选择异常类型" clearable style="width: 100%">
            <el-option v-for="item in exTypeOptions" :key="item.code" :label="item.name" :value="item.name" />
          </el-select>
        </el-form-item>
        <el-form-item label="严重程度">
          <el-select v-model="createForm.severity" placeholder="请选择严重程度" clearable style="width: 100%">
            <el-option v-for="item in exSeverityOptions" :key="item.code" :label="item.name" :value="item.name" />
          </el-select>
        </el-form-item>
        <el-form-item label="描述">
          <el-input type="textarea" v-model="createForm.desc" style="width: 100%" rows="3" />
        </el-form-item>
        <el-form-item label="图片">
          <el-upload
            :auto-upload="false"
            list-type="picture-card"
            :file-list="createForm.images"
            :on-remove="handleRemoveImage"
            :on-change="handleImageChange"
            style="width: 100%"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
        <div style="text-align: center; margin-top: 16px;">
          <el-button @click="showCreateDialog = false">取消</el-button>
          <el-button type="primary" @click="submitCreate">提交</el-button>
        </div>
      </el-form>
    </el-dialog>

    <!-- 异常详情弹窗 -->
    <el-dialog v-model="showDetailDialog" title="异常详情" width="600px">
      <div v-if="detail" class="detail-desc-wrap">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="异常单号">{{ detail.id }}</el-descriptions-item>
          <el-descriptions-item label="订单号">{{ detail.order_id }}</el-descriptions-item>
          <el-descriptions-item label="客户">{{ detail.customer }}</el-descriptions-item>
          <el-descriptions-item label="异常类型">{{ detail.type }}</el-descriptions-item>
          <el-descriptions-item label="严重程度">{{ detail.severity }}</el-descriptions-item>
          <el-descriptions-item label="状态">{{ detail.status }}</el-descriptions-item>
          <el-descriptions-item label="上报时间">{{ detail.reportTime }}</el-descriptions-item>
          <el-descriptions-item label="处理措施">{{ detail.action || '无' }}</el-descriptions-item>
          <el-descriptions-item label="责任人">{{ detail.responsible || '无' }}</el-descriptions-item>
          <el-descriptions-item label="期望完成">{{ detail.expectedDate || '无' }}</el-descriptions-item>
          <el-descriptions-item label="备注">{{ detail.notes || '无' }}</el-descriptions-item>
          <el-descriptions-item label="描述" :span="2">{{ detail.desc }}</el-descriptions-item>
          <el-descriptions-item label="图片" :span="2">
            <div v-if="detailImages.length" class="detail-img-list">
              <el-image
                v-for="img in detailImages"
                :key="img"
                :src="img"
                style="width: 80px; margin-right: 8px; border-radius: 6px; box-shadow: 0 2px 8px #eee;"
                fit="cover"
                :preview-src-list="detailImages"
              />
            </div>
            <span v-else>无</span>
          </el-descriptions-item>
        </el-descriptions>
      </div>
      <template #footer>
        <el-button @click="showDetailDialog = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { fetchExceptionList, fetchExceptionDetail, reportException, sendExceptionMessage, getEXTypeList, getEXSeverity, uploadExceptionImage, getTaskPackages, getTaskPackageDetail } from '@/assets/delivery.js'

// 筛选条件
const filters = reactive({ type: '', severity: '', keyword: '' })
const pagination = reactive({ page: 1, size: 3, total: 0 })
const exceptionList = ref([])
const showCreateDialog = ref(false)
const createForm = reactive({ order_id: '', type: '', severity: '', desc: '', images: [], customer: '', phone: '', address: '' })
const showDetailDialog = ref(false)
const detail = ref(null)
const detailImages = ref([])
const newMessage = ref('')
const exTypeOptions = ref([])
const exSeverityOptions = ref([])
const exStatusOptions = ref([])

// 配送中订单列表（实际应从接口或父组件传入，这里mock）
const deliveringOrders = ref([
  { order_id: 'ETT138692', customer: '赵桂坤', phone: '18731077217', address: '河北省保定市莲池区' },
  { order_id: 'XYX353411', customer: '柴硕林', phone: '15128036265', address: '柴硕林家门口' }
])

// 二级联动相关
const deliveringPackages = ref([]) // 配送中任务包
const packageOrders = ref([])      // 当前选中任务包下的订单

const fetchExceptionListApi = async (data) => {
  const res = await fetchExceptionList(data)
  if (res.data && res.data.code === 200 && res.data.data) {
    exceptionList.value = (res.data.data.records || []).map(item => ({
      id: item.id,
      order_id: item.trackingId || item.order_id,
      type: item.type,
      status: item.status,
      created_at: item.reportTime || item.created_at,
      desc: item.description || item.desc,
      images: item.images || [],
      messages: item.messages || []
    }))
    pagination.total = res.data.data.total || 0
  } else {
    exceptionList.value = []
    pagination.total = 0
  }
}
const resetFilters = () => {
  filters.type = ''
  filters.severity = ''
  filters.keyword = ''
  fetchList()
}
const handleImageUpload = async (option) => {
  const formData = new FormData()
  formData.append('image', option.file)
  const res = await uploadExceptionImage(formData)
  if (res.data && res.data.code === 200) {
    createForm.images.push({
      name: option.file.name,
      url: res.data.data.url
    })
    option.onSuccess(res.data, option.file)
  } else {
    option.onError(new Error(res.data.message || '上传失败'))
  }
}
const handleRemoveImage = (file, fileList) => {
  createForm.images = fileList
}
const handleImageChange = (file, fileList) => {
  createForm.images = fileList
}
const submitCreate = async () => {
  // 1. 先新建异常单，参数字段与后端一致
  const res = await reportException({
    trackingId: createForm.order_id,
    customer: createForm.customer,
    type: createForm.type,
    severity: createForm.severity,
    description: createForm.desc
  })
  if (res.data && res.data.code === 200) {
    const reportId = res.data.data.id || res.data.data?.reportId || res.data.data
    // 2. 上传所有图片
    for (const file of createForm.images) {
      const formData = new FormData()
      formData.append('report_id', reportId)
      formData.append('image', file.raw)
      await uploadExceptionImage(formData)
    }
    ElMessage.success('新建成功')
    showCreateDialog.value = false
    createForm.images = []
    fetchList()
  } else {
    ElMessage.error(res.data.message || '新建失败')
  }
}
const openDetail = async (row) => {
  const res = await fetchExceptionDetail(row.id)
  if (res.data && res.data.code === 200 && res.data.data) {
    const d = res.data.data
    detail.value = {
      id: d.report.id,
      order_id: d.report.trackingId,
      customer: d.report.customer,
      type: d.report.type,
      severity: d.report.severity,
      status: d.report.status,
      desc: d.report.description,
      reportTime: d.report.reportTime,
      action: d.report.action,
      responsible: d.report.responsible,
      expectedDate: d.report.expectedDate,
      notes: d.report.notes
    }
    detailImages.value = d.images || []
    showDetailDialog.value = true
  } else {
    ElMessage.error(res.data.message || '获取详情失败')
  }
}
const sendMessage = async () => {
  if (!newMessage.value) return
  const res = await sendExceptionMessage({
    exception_id: detail.value.id,
    content: newMessage.value
  })
  if (res.data && res.data.code === 200) {
    detail.value.messages.push({ id: Date.now(), sender: '配送员', content: newMessage.value, time: new Date().toLocaleString() })
    newMessage.value = ''
  } else {
    ElMessage.error(res.data.message || '发送失败')
  }
}
const handleOrderChange = (orderId) => {
  const order = packageOrders.value.find(o => o.orderNumber === orderId)
  if (order) {
    createForm.customer = order.customerName || order.customer || order.name || ''
    createForm.phone = order.customerPhone || order.phone || order.tel || ''
    createForm.address = order.address || order.deliveryAddress || order.addr || ''
  } else {
    createForm.customer = ''
    createForm.phone = ''
    createForm.address = ''
  }
}
const handlePackageChange = async (packageId) => {
  createForm.order_id = '' // 清空订单号
  packageOrders.value = []
  if (!packageId) return
  const res = await getTaskPackageDetail(packageId)
  if (res.data && res.data.data && res.data.data.orders) {
    packageOrders.value = res.data.data.orders
    console.log('packageOrders:', packageOrders.value) // 打印调试
  }
}
const fetchList = () => {
  fetchExceptionListApi({
    type: filters.type,
    severity: filters.severity,
    keyword: filters.keyword,
    page: pagination.page,
    size: pagination.size
  })
}
const fetchDeliveringPackages = async () => {
  const res = await getTaskPackages({ page: 1, size: 100, status: 'delivering' })
  if (res.data && res.data.data && res.data.data.records) {
    deliveringPackages.value = res.data.data.records
  }
}
onMounted(() => {
  fetchList()
  fetchDeliveringPackages()
  // 拉取异常类型和严重程度
  getEXTypeList().then(res => {
    if (res.data && res.data.code === 200) {
      exTypeOptions.value = res.data.data
    }
  })
  getEXSeverity().then(res => {
    if (res.data && res.data.code === 200) {
      exSeverityOptions.value = res.data.data
    }
  })
  // 拉取异常状态
  if (typeof getEXStatusList === 'function') {
    getEXStatusList().then(res => {
      if (res.data && res.data.code === 200) {
        exStatusOptions.value = res.data.data
      }
    })
  }
})
</script>
<style scoped>
.exception-page {
  padding: 32px 24px 24px 24px;
  background: #f8fafc;
  min-height: 100vh;
}
.filter-form {
  background: #fff;
  padding: 18px 24px 8px 24px;
  border-radius: 10px;
  box-shadow: 0 2px 8px #f0f1f2;
  margin-bottom: 18px;
}
.create-btn-bar {
  text-align: right;
  margin-bottom: 16px;
}
.exception-table {
  background: #fff;
  border-radius: 10px;
  box-shadow: 0 2px 8px #f0f1f2;
  margin-bottom: 18px;
}
::v-deep(.table-header) {
  font-weight: bold;
  font-size: 15px;
  background: #f3f4f6;
}
.create-form {
  padding: 12px 0 0 0;
}
.detail-desc-wrap {
  background: #f9fafb;
  border-radius: 8px;
  padding: 12px 8px 8px 8px;
}
.detail-img-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-top: 4px;
}
</style> 